package com.mano.mall.gateway.filters;

import com.mano.commons.web.utils.HttpRequestUtil;
import com.mano.mall.common.constants.Constants;
import com.mano.mall.gateway.builder.director.GatewayDirector;
import com.mano.mall.gateway.constant.FilterConstant;
import com.mano.mall.gateway.handler.ResponsibilityClient;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author: zj
 * @Description: APP网关拦截器
 * @Date: Created in 16:29 2020/11/2
 * @Modified By:
 */
@Component
@Slf4j
public class AppGatewayFilter extends ZuulFilter {

//    @Autowired
//    private BlacklistMapper blacklistMapper;

//    @Autowired
//    private GatewayDirector gatewayDirector;

    @Autowired
    private ResponsibilityClient responsibilityClient;

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();
        response.setContentType("UTF-8");

        // 获取ip地址
        String ipAddres = HttpRequestUtil.getIpAddr(request);
        if (StringUtils.isEmpty(ipAddres)) {
            resultError(ctx, "未能够获取到ip地址");
        }
         // 建造者模式 处理
//        gatewayDirector.direcot(ctx, ipAddres, response, request);

        // 使用责任链处理
        responsibilityClient.responsibility(ctx,ipAddres,request,response);

        // 过滤非法参数
//        Map<String, List<String>> filterParameters = HttpRequestUtil.filterParameters(request);
//        ctx.setRequestQueryParams(filterParameters);

        return null;
    }

    private void resultError(RequestContext ctx, String errorMsg) {
        ctx.setResponseStatusCode(Constants.HTTP_NOT_AUTH);
        ctx.setSendZuulResponse(false);
        ctx.setResponseBody(errorMsg);

    }



    @Override
    public boolean shouldFilter() {
        return true;
    }


    @Override
    public String filterType() {
        return FilterConstant.FILTER_TYPE_PRE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }
}
